package com.xiong.wuliao.mainfragment;


import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xiong.wuliao.LoginActivity;
import com.xiong.wuliao.MoreActivity;
import com.xiong.wuliao.R;
import com.xiong.wuliao.util.FragmentMineUtil;
import com.xiong.wuliao.view.MineScrollView;

/**
 * 第四个页面：个人中心页面
 */
public class MineFragment extends Fragment implements MineScrollView.MyScrollListener, ViewPager.OnPageChangeListener, View.OnClickListener {
    private TextView mineTextViewMore; // “更多”
    private RelativeLayout mineLoginRelative; // 点击跳转到登陆页面，如果已经登陆在点击可以选择退出
    private RelativeLayout mineNewsRelative; // 已经登陆点击可查看新消息，没有登陆点击会跳转到登陆页面
    private boolean isLogin = false; // 这里留来判断是否已经登陆
	SharedPreferences sp;
	private TextView myTextViewUserName;

    private MineScrollView myScrollView;
    private LinearLayout myTabLayoutStop; // 上面部分显示的Tab不可移动
    private TabLayout myTabLayoutMove; // 中间部分显示的Tab可移动
    private ViewPager myViewPager;
    private MyFragmentPagerAdapter adapter; // ViewPager的适配器

    private String[] tabList = {"喜欢的商品", "喜欢的专题"};

    private RelativeLayout head; // 头部
    private int topDistance; // 获取绿色到顶部布局的距离
    private int height; // 顶部黑色栏的高度

    private Button mineBtnOne; // 顶替TabLayout的左控件
    private Button mineBtnTwo; // 顶替TabLayout的右控件
    private View mineBottomLine; // 顶替TabLayout下划线的View
    LinearLayout.LayoutParams params;
    private int screenWidth;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        findView(view);
		sp = getActivity().getSharedPreferences("kkUser", Context.MODE_PRIVATE);
		isLogin = sp.getBoolean("isLogin",false);
		if (isLogin){
			myTextViewUserName.setText(sp.getString("userName","用户名"));
		}
        getWidthAndHeight();
        return view;
    }

	@Override
	public void onResume() {
		super.onResume();
		isLogin = sp.getBoolean("isLogin",false);
		if (isLogin){
			myTextViewUserName.setText(sp.getString("userName","用户名"));
		}
	}

	@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
		// 更换tab
        tabLayoutChange();
		// 设置虚假的Tab
        btnChange();
        setMyAdapter();
        setListener();

    }

    /**
     * 设置虚假的Tab
     */
    private void btnChange() {
        initScreenWidth();
        setViewFlingWidth();
        mineBtnOne.setTextColor(Color.RED);
        mineBtnTwo.setTextColor(Color.BLACK);

    }

    /**
     * 获取屏幕的宽
     */
    private void initScreenWidth() {
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        screenWidth = mDisplayMetrics.widthPixels;
    }

    /**
     * 设置监听事件
     */
    private void setListener() {
        // 给ScrollView设置监听
        myScrollView.setMyScrollListener(this);
        // 设置ViewPager的滑动更换Tab的监听
        myViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(myTabLayoutMove));
        // 设置虚假Tab的ViewPager的监听
        myViewPager.addOnPageChangeListener(this);
        // 设置TabLayout的选择监听,与ViewPager关联
        myTabLayoutMove.setOnTabSelectedListener(new MyTabSelectedListener());
        // 给“更多”设置监听事件，跳到设置页面
        mineTextViewMore.setOnClickListener(this);
        // 头像部分的点击事件
        mineLoginRelative.setOnClickListener(this);
        // 我的消息部分的点击事件
        mineNewsRelative.setOnClickListener(this);
    }

    /**
     * 设置适配器
     */
    private void setMyAdapter() {
        adapter = new MyFragmentPagerAdapter(getChildFragmentManager());
        // 设置适配器
        myViewPager.setAdapter(adapter);
        // 设置预加载2个
        myViewPager.setOffscreenPageLimit(2);
        // 设置默认显示第一个fragment
        myViewPager.setCurrentItem(0);
        // 设置关联
        myTabLayoutMove.setupWithViewPager(myViewPager);
        myTabLayoutMove.setTabsFromPagerAdapter(adapter);
    }

    /**
     * tab的更换
     */
    private void tabLayoutChange() {
        myTabLayoutMove.setTabMode(TabLayout.MODE_FIXED);
        for (int index = 0; index < tabList.length; index++) {
            myTabLayoutMove.addTab(myTabLayoutMove.newTab().setText(tabList[index]));
        }
    }

    //***********************************************************************

    /**
     * 虚假Tab的下划线跟随ViewPager的滑动而改变位置
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        params.leftMargin = (int) (position + positionOffset) * params.width;
        mineBottomLine.setLayoutParams(params);
    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 设置滑动块的宽度
     */
    private void setViewFlingWidth() {
        //这个里面宽度设置成屏幕的3分之1   高度还是原来的
        params = new LinearLayout.LayoutParams(screenWidth / 2, mineBottomLine.getLayoutParams().height);
        mineBottomLine.setLayoutParams(params);
    }

    /**
     * 普通按钮的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mineTextViewMore:   // 点击更多，跳转到
                Intent intent = new Intent(getActivity(), MoreActivity.class);
                startActivity(intent);
                break;
            case R.id.mineLoginRelative:
				isLogin = sp.getBoolean("isLogin",false);
                if (!isLogin) { // 没有登陆，到登陆页面
                    Intent intent1 = new Intent(getActivity(),LoginActivity.class);
                    startActivity(intent1);
                } else { // 已经登陆
                    myDialog();
                }
                break;
            case R.id.mineNewsRelative:
				isLogin = sp.getBoolean("isLogin",false);
                if (!isLogin) { // 没有登陆
                    Intent intent2 = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent2);
                } else { // 已经登陆
                    myDialog();
                }
                break;

        }
    }

    /**
     * 已经登陆后点击头像弹出的Dialog
     */
    private void myDialog() {
        // 实例化一个建造者对象
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (getActivity(), android.R.layout.simple_list_item_1, new String[]{"查看资料", "退出登录"});
        // 设置一个列表
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        Toast.makeText(getActivity(), "已经查看资料了", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
						//SharedPreferences sp = getActivity().getSharedPreferences("kkUser", Context.MODE_PRIVATE);
						SharedPreferences.Editor editor = sp.edit();
						editor.putBoolean("isLogin", false);
						editor.putString("id", "");
						editor.putString("userName", "");
						editor.putString("passWord", "");
						editor.putString("phone", "");
						editor.commit();
						myTextViewUserName.setText("用户名");
                        break;
                }
            }
        });

        // 建造一个对话框dialog对象并显示
        AlertDialog dialog = builder.create();
        dialog.show();
    }


    //***********************************************************************

    /**
     * TabLayout的选择监听事件
     */
    private class MyTabSelectedListener implements TabLayout.OnTabSelectedListener {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            int position = tab.getPosition();
            myViewPager.setCurrentItem(position);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    }

    /**
     * Viewpager的适配器
     */
    private class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return FragmentMineUtil.getFragments().get(position);
        }

        @Override
        public int getCount() {
            return FragmentMineUtil.getFragmentSize();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabList[position];
        }
    }

    /**
     * 初始化控件
     */
    private void findView(View view) {
        mineLoginRelative = (RelativeLayout) view.findViewById(R.id.mineLoginRelative);
        mineNewsRelative = (RelativeLayout) view.findViewById(R.id.mineNewsRelative);
        mineTextViewMore = (TextView) view.findViewById(R.id.mineTextViewMore);
		// 用户名
		myTextViewUserName = (TextView) view.findViewById(R.id.myTextViewUserName);

		myScrollView = (MineScrollView) view.findViewById(R.id.scv);
        head = (RelativeLayout) view.findViewById(R.id.head);
        myViewPager = (ViewPager) view.findViewById(R.id.mineViewPager);
        myTabLayoutStop = (LinearLayout) view.findViewById(R.id.mineTableLayoutStop);
        myTabLayoutMove = (TabLayout) view.findViewById(R.id.mineTableLayoutMove);

        mineBtnOne = (Button) view.findViewById(R.id.mineBtnOne);
        mineBtnTwo = (Button) view.findViewById(R.id.mineBtnTwo);
        mineBottomLine = view.findViewById(R.id.mineBottomLine);
    }

    /**
     * 获取布局中顶部标题和可移动标题的高和顶部距离
     */
    private void getWidthAndHeight() {
        ViewTreeObserver observer = myTabLayoutMove.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {
                topDistance = myTabLayoutMove.getTop();
                myTabLayoutMove.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
        ViewTreeObserver observer1 = head.getViewTreeObserver();
        observer1.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {
                height = head.getMeasuredHeight();
                head.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    }

    /**
     * 接口回调，传递页面的状态，判断tab是否停留显示
     *
     * @param distance
     */
    @Override
    public void sendDistanceY(int distance) {
        if (distance >= topDistance - height) {
            myTabLayoutStop.setVisibility(View.VISIBLE);
        } else {
            myTabLayoutStop.setVisibility(View.GONE);
        }
    }


}
